/*
 * @(#)Processer.java
 *
 */

package diablo3.process;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import diablo3.support.Identifer;
import diablo3.support.Util;

/**
 * description
 * 
 * @author huangyixiang
 * @version 2012-8-28
 */
public class Processer {

	private static final Log LOG = LogFactory.getLog(Processer.class);

	public static void main(String[] args) {
		
		Processer processer = new Processer();
		processer.startProcessInPath("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");
		
		
//		Process process = null;
//		try {
//			process = Runtime.getRuntime().exec("cmd.exe /c tasklist -v /NH /FI \"IMAGENAME eq QQ.exe\"");
//			BufferedReader input = new BufferedReader(new InputStreamReader(
//					process.getInputStream(),"GBK"));
//			String line = " ";
//			while ((line = input.readLine()) != null) {
//				System.out.println(line);
//			}
//			input.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		/*Processer processer = new Processer();
		MyProcess myProcess = null;
		myProcess = processer.getProcess("QQ.exe");
		System.out.println(myProcess);*/
	}
	
	public void monitoringProcess(String name , int cycleTime) throws InterruptedException{
		MyProcess lastMyProcess = null;
		while(true){
			MyProcess myProcess = getProcess(name);
			if(lastMyProcess != null){
				//上次不为空，这次为空，说明正在重启
				if(myProcess == null){
					lastMyProcess = new MyProcess(name, name + " 00:00:00");
				}
				//这次不为空,说明重启好了
				else if(myProcess.getTimer().compare(lastMyProcess.getTimer()) != 1){
					LOG.info(name + "重启了");
					lastMyProcess = myProcess;
				}
			}
			else{
				lastMyProcess = myProcess;
			}
			Thread.sleep(cycleTime * 1000);
		}
	}
	
	public MyProcess getProcess(String name) {
		if(Util.isBlank(name)){
			return null;
		}
		Process process = null;
		MyProcess myProcess = null;
		try {
			process = Runtime.getRuntime().exec("cmd.exe /c tasklist -v /NH /FI \"IMAGENAME eq " + name.trim() + "\"");
			BufferedReader input = new BufferedReader(new InputStreamReader(
					process.getInputStream(),"GBK"));
			String line = "";
			int count = 0;
			while ((line = input.readLine()) != null) {
				if(Util.isBlank(line) ||
						!line.startsWith(name.trim())){
					continue;
				}
				if(count >= 1){
					LOG.info("有" +  count + "个 " + name + " 进程");
					break;
				}
				myProcess = new MyProcess(name, line);
				count++;
			}
			if(count == 0){
				LOG.info("没有发现"+ name +"进程");
			}
			input.close();
		} catch (IOException e) {
			LOG.error(e.getMessage(),e);
		}
		return myProcess;
	}
	
	public Process exec(String order, boolean newCmd){
		try {
			String cmdOrder = "cmd.exe /c " + (newCmd ? "start " : "") + order;
			return Runtime.getRuntime().exec(cmdOrder);
		} catch (IOException e) {
			LOG.error("错误的命令 (error order) : " + order,e);
		}
		return null;
	}
	
	public Process execBatch(String[] orders, boolean newCmd){
		String userPath = System.getProperty("user.dir") + File.separator;
		String fileName = userPath + String.valueOf(Identifer.generateIdentifer()) + ".bat";
		File file = new File(fileName);
		if(file.exists()){
			file.delete();
		}
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file);
			String fileContent = "";
			for(String s : orders){
				fileContent += s + "\r\n"; 
			}
			fileWriter.write(fileContent);
			fileWriter.flush();
		} catch (IOException e) {
			LOG.error(e.getMessage());
		}
		finally{
			if(fileWriter != null){
				try {
					fileWriter.close();
				} catch (IOException e) {
					LOG.error(e.getMessage());
				}
			}
		}
		Process process = exec(fileName, true);
		Util.threadSleep(1);
		file.delete();
		return process;
	}
	
	
	
	public void killProcess(String processName){
		String order = "taskkill /F /IM " + processName;
		exec(order, true);
	}
	
	
	public void startProcess(String processName){
		exec(processName, true);
	}
	
	/**
	 * 进入目录启动进程
	 * @param processName
	 */
	public void startProcessInPath(String processName){
		processName = processName.replaceAll("/", "\\\\");
		String root = processName.substring(0, 2);
		String path = processName.substring(0, processName.lastIndexOf("\\") + 1);
		String exe = processName.substring(processName.lastIndexOf("\\") + 1);
		
		String[] orders = new String[]{
				root,
				"cd " + path,
				"cmd /c start " + exe,
				"exit"
		};
		execBatch(orders, true);
	}
	
	public boolean processExist(String processName){
		MyProcess myProcess = this.getProcess(processName);
		return myProcess != null;
		
	}
}
